using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Drugstores;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Drugstores
{
    /// <summary>
    /// 更新药店命令处理器
    /// </summary>
    public class UpdateDrugstoreCommandHandler : IRequestHandler<UpdateDrugstoreCommand, ApiResult<int>>
    {
        /// <summary>
        /// 药店仓储
        /// </summary>
        private readonly IBaseRepository<PharmacyManagementModel> _drugstoreRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<UpdateDrugstoreCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="drugstoreRepository">药店仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public UpdateDrugstoreCommandHandler(IBaseRepository<PharmacyManagementModel> drugstoreRepository, IMapper mapper, ILogger<UpdateDrugstoreCommandHandler> logger)
        {
            _drugstoreRepository = drugstoreRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新药店命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateDrugstoreCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理药店更新命令，药店ID：{Id}，药店名称：{PharmacyName}", request.Id, request.PharmacyName);

                // 验证药店是否存在
                var existingDrugstore = _drugstoreRepository.GetAll().FirstOrDefault(x => x.Id == request.Id);
                if (existingDrugstore == null)
                {
                    _logger.LogWarning("药店不存在，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "药店不存在！",
                        data = 0
                    };
                }

                // 验证药店名称是否与其他药店重复（排除自身）
                var existingDrugstores = _drugstoreRepository.GetAll()
                    .Where(x => x.PharmacyName == request.PharmacyName && x.Id != request.Id);

                if (existingDrugstores.Any())
                {
                    _logger.LogWarning("药店名称已存在，名称：{PharmacyName}", request.PharmacyName);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "药店名称已存在！",
                        data = 0
                    };
                }

                _logger.LogDebug("药店验证通过，开始更新药店信息");

                // 更新药店信息
                existingDrugstore.PharmacyName = request.PharmacyName;
                existingDrugstore.PharmacyImage = request.PharmacyImage;
                existingDrugstore.IsRecommend = request.IsRecommend;
                existingDrugstore.PharmacyAreas = request.PharmacyAreas;
                existingDrugstore.PharmacyAddress = request.PharmacyAddress;
                existingDrugstore.PharmacyDescription = request.PharmacyDescription;
                existingDrugstore.PharmacyPhone = request.PharmacyPhone;
                existingDrugstore.UpdatedTime = DateTime.Now;
                existingDrugstore.UpdatedBy = 1; // 这里应该从当前用户上下文获取

                _logger.LogDebug("药店信息更新完成，准备保存到数据库");

                // 保存到数据库
                var result = await _drugstoreRepository.UpdateAsync(existingDrugstore);
                _logger.LogInformation("数据库更新完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("药店更新成功，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "药店更新成功",
                        data = request.Id
                    };
                }
                else
                {
                    _logger.LogWarning("药店更新失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "药店更新失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "药店更新过程中发生异常，药店ID：{Id}", request.Id);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"药店更新异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}